package com.goat.rxcachedemo

import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.util.Log
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {
    var sum = { a: Int, b: Int -> a + b }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        pull.setOnClickListener {
            textView.text=""
            pullData()
        }
        cacha.setOnClickListener{
            textView.text=""
            ApiManager.getInstence().getService(true).province.subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread()).subscribe(object : Observer<ApiRes<List<Province>>> {
                override fun onSubscribe(d: Disposable) {
                    sum(1, 3) + 3
                }

                override fun onComplete() {
                }

                override fun onError(e: Throwable) {
                    loge<MainActivity>(log = e)
                }

                override fun onNext(t: ApiRes<List<Province>>) {
                    textView.text = "缓存数据"+t.toString()
                    for (retDatum in t.retData) {
                        loge<MainActivity>(log = retDatum.toString())
                    }
                    pullData()
                }
            })
        }

    }


    fun  pullData(){
        ApiManager.getInstence().getService(false).province.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread()).subscribe(object :Observer<ApiRes<List<Province>>>{
            override fun onNext(t: ApiRes<List<Province>>) {
                for (retDatum in t.retData) {
                    loge<MainActivity>(log = retDatum.toString())
                }
                textView.text = "网络请求的 数据"+t.toString()
            }

            override fun onError(e: Throwable) {
            }

            override fun onSubscribe(d: Disposable) {
            }

            override fun onComplete() {
            }

        })
    }
}

/**
 * 打印loge
 * @param tag 默认取class.simpleName
 * @param log 打印log
 */
inline fun <reified T> T.loge(tag: String = T::class.simpleName!!, log: Any) {
    if (BuildConfig.DEBUG) Log.e(T::class.simpleName, log.toString())
}